package team.knowers.qzh.qzhgrame.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import team.knowers.qzh.qzhgrame.dao.entity.CourseDO;
import team.knowers.qzh.qzhgrame.dao.entity.SectionDO;
import team.knowers.qzh.qzhgrame.dao.entity.UserDO;
import team.knowers.qzh.qzhgrame.dao.mapper.UserMapper;
import team.knowers.qzh.qzhgrame.dto.req.UserLoginReqDTO;
import team.knowers.qzh.qzhgrame.dto.resp.UserLoginRespDTO;
import team.knowers.qzh.qzhgrame.dto.resp.UserMessageRespDTO;
import team.knowers.qzh.qzhgrame.service.UserGrameService;
import team.knowers.qzh.qzhgrame.common.convention.exception.ClientException;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wt
 */
@Service
@RequiredArgsConstructor
public class UserGrameServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserGrameService {
    private final StringRedisTemplate stringRedisTemplate;
    private final SectionGrameServiceImpl sectionGrameService;
    private final CourseGrameServiceImpl courseGrameService;

    /**
     * 检查用户是否已登录的方法
     */
    @Override
    public boolean isUserLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_grame_" + username, token) != null;
    }


    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new team.knowers.qzh.qzhserver.common.convention.exception.ClientException("用户不存在");
        }
        Boolean hasLogin = stringRedisTemplate.hasKey("login_grame_" + requestParam.getUsername());
        if (hasLogin != null && hasLogin) {
            throw new team.knowers.qzh.qzhserver.common.convention.exception.ClientException("用户已登录");
        }
        /**
         * Hash
         * Key：login_用户名
         * Value：
         *  Key：token标识
         *  Val：JSON 字符串（用户信息）
         */
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_grame_" + requestParam.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire("login_grame_" + requestParam.getUsername(), 30L, TimeUnit.DAYS);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public boolean logout(String username, String token) {
        if (isUserLogin(username, token)) {
            stringRedisTemplate.delete("login_grame_" + username);
            return true;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }

    @Override
    public String ban(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username)
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        userDO.setRole(1);
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class).eq(UserDO::getUsername, username)
                .eq(UserDO::getDelFlag, 0)
                .set(UserDO::getRole, 1);
        baseMapper.update(userDO, updateWrapper);
        return (username + "已被封禁");
    }

    @Override
    public String relieve(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username)
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        userDO.setRole(0);
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class).eq(UserDO::getUsername, username)
                .eq(UserDO::getDelFlag, 0)
                .set(UserDO::getRole, 0);
        baseMapper.update(userDO, updateWrapper);
        return (username + "已被解除封禁");
    }

    @Override
    public UserMessageRespDTO showUser(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username)
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        UserMessageRespDTO userMessageRespDTO = new UserMessageRespDTO();

        if (userDO != null) {
            userMessageRespDTO.setFans(userDO.getFans());
            userMessageRespDTO.setLikes(userDO.getLikes());
            userMessageRespDTO.setUserId(userDO.getId());
            LambdaQueryWrapper<CourseDO> queryWrapper1 = Wrappers.lambdaQuery(CourseDO.class).eq(CourseDO::getUserId, userDO.getId())
                    .eq(CourseDO::getDelFlag, 0);
            List<CourseDO> courseDOList = courseGrameService.getBaseMapper().selectList(queryWrapper1);
            LambdaQueryWrapper<SectionDO> queryWrapper2=Wrappers.lambdaQuery(SectionDO.class).eq(SectionDO::getAuthorId,userDO.getId())
                    .eq(SectionDO::getDelFlag,0);
            List<SectionDO> sectionDOS=sectionGrameService.getBaseMapper().selectList(queryWrapper2);
            userMessageRespDTO.setCourseNumber(courseDOList.size());
            userMessageRespDTO.setVersionNumber(sectionDOS.size());
        }

        return userMessageRespDTO;
    }

}

